/**
 * 
 */
package com.jinmei.security.interceptor;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.StrutsStatics;

import com.jinmei.utils.JinmeiConsts;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/**
 * @author richard
 *
 */
public class AppAuthenticationInterceptor extends AbstractInterceptor {
	
	private static final long serialVersionUID = 1663928135115450944L;
	private static final Logger log = Logger.getLogger(AppAuthenticationInterceptor.class);

	@Override  
    public String intercept(ActionInvocation invocation) throws Exception {  
        HttpServletRequest request =
        		(HttpServletRequest) invocation.getInvocationContext().get(StrutsStatics.HTTP_REQUEST);
        // do not check session id when login or sysnc employees
        if (request.getRequestURI().endsWith("login") ||
        		request.getRequestURI().endsWith("sysncEmployees")) {
        	return invocation.invoke(); 
        }
        
        Map<String, Object> session = ActionContext.getContext().getSession();
        String serverSessionid = (String) session.get(JinmeiConsts.USER_SESSIONID);
        String clientSessionId = request.getSession().getId();
        if (!StringUtils.equals(clientSessionId, serverSessionid)) {  
            log.info("not logged in or session time out.");
            request.setAttribute("msg", "not logged in or session timeout");
            return Action.SUCCESS;  
        } else {  
        	// continue to invoke action
            return invocation.invoke();  
        }  
    }  

}
